// pages/videoStudy/index.js
const app = getApp()// 云：add this before every page //
const HTTP = require('../../utils/http')
const API = require('../../utils/api')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    safeBottom: app.globalData.safeBottom, // 云：add this before every page //
    safeTop: app.globalData.safeTop,

    // 点赞和收藏
    stared: false,
    liked: false,

    showFoot: false,
    detailData: {},
    courseId: "",
    video: '',
    // video: 'https://vd4.bdstatic.com/mda-id9czn5517wu43qj/sc/mda-id9czn5517wu43qj.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1678386307-0-0-95718b0fb60d51482c6475eafc5e5778&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=3307537314&vid=11190352271740445395&abtest=107354_1-107353_1&klogid=3307537314',
    initialTime: 0,
    currentTime: 0,
    videoDuration: 0,
    videoDurationMin: 0,
    videoDurationSec:0
  },


    // 分享
    tapShare(){
      console.log("点击页面分享按钮!")
      // wx.showShareMenu()
      wx.showModal({
        title: '分享课程',
        content: '请点击小程序右上角胶囊分享课程!',
        showCancel: false,
        confirmText: '我知道了'
      })
    },
  
    // 点赞
    tapLike(){
      if(this.data.liked){
        let that=this
        wx.showModal({
          title: '取消点赞',
          content: '您确定需要取消点赞吗？',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定取消点赞')
              that.likeTrueOrFalse(
                {
                  id: that.data.courseId,
                  liked: false
                }
              )
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
      else{
        this.likeTrueOrFalse(
          {
            id: this.data.courseId,
            liked: true
          }
        )
      }
    },
  
    // 收藏
    tapStar(){
      if(this.data.stared){
        let that=this
        wx.showModal({
          title: '取消收藏',
          content: '您确定需要取消收藏吗？',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定取消收藏')
              that.starTrueOrFalse(
                {
                  id: that.data.courseId,
                  stared: false
                }
              )
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
      else{
        this.starTrueOrFalse(
          {
            id: this.data.courseId,
            stared: true
          }
        )
      } 
    },
  
    // 确定或者取消点赞
    likeTrueOrFalse(data){
      wx.request({
        url: API.LikeCourse,
        header:{
          "Authorization": 'Bearer '+wx.getStorageSync('accessTokenData').accessToken
        },
        method: "put",
        data:data,
        success: (res) => {
          console.log("调用点赞接口返回的信息是：",res)
          if(data.liked){
            if(res.data.code===0){
              wx.showToast({
                title: '点赞成功',
              })
              this.setData({
                liked: true
              })
            }
            else{
              wx.showToast({
                title: '点赞出错',
              })
            }
          }
          else{
            if(res.data.code===0){
              wx.showToast({
                title: '取消点赞成功',
              })
              this.setData({
                liked: false
              })
            }
            else{
              wx.showToast({
                title: '取消点赞出错',
              })
            }
          }
        },
        fail: (err) => {
          wx.showModal({
            title: '提示',
            content: JSON.stringify(err),
          })
          console.log(err);
        },
        complete:()=>{
          
        }
      })
    },
  
    // 确定或者取消收藏
    starTrueOrFalse(data){
      wx.request({
        url: API.StarCourse,
        header:{
          "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken
        },
        method: "put",
        data:data,
        success: (res) => {
          console.log("调用收藏接口返回的信息是：",res)
          if(data.stared){
            if(res.data.code===0){
              wx.showToast({
                title: '收藏成功',
              })
              this.setData({
                stared: true
              })
            }
            else{
              wx.showToast({
                title: '收藏出错',
              })
            } 
          }
          else{
            if(res.data.code===0){
              wx.showToast({
                title: '取消收藏成功',
              })
              this.setData({
                stared: false
              })
            }
            else{
              wx.showToast({
                title: '取消收藏出错',
              })
            }
          }
        },
        fail: (err) => {
          wx.showModal({
            title: '提示',
            content: JSON.stringify(err),
          })
          console.log(err);
        },
        complete:()=>{
          
        }
      })
    },

  //视频播放完成
  finish() {
    this.setData({
      showFoot: true
    })
  },
  //视频播放进度时间
  playTimeUpdate(event){
    // console.log('视频播放到：', Math.floor(event.detail.currentTime),"s")
    let currentTimeUpdate=Math.floor(event.detail.currentTime)
    if(currentTimeUpdate>this.data.currentTime){
      this.setData({
        currentTime: currentTimeUpdate
      })
      console.log('视频播放到：', this.data.currentTime,"s")
    }
  },
  // 获取视频信息
  videoMetaData(event){
    console.log('视频信息为：',event.detail)
    this.setData({
      videoDuration: event.detail.duration,
      videoDurationMin: Math.floor(event.detail.duration/60),
      videoDurationSec: Math.floor(event.detail.duration%60),
      initialTime: this.data.detailData.playerTimestamp
    })
    let video = wx.createVideoContext('video');
    video.seek(this.data.detailData.playerTimestamp)
  },

  replay() {
    const video = wx.createVideoContext('video');
    video.play()
    this.setData({
      showFoot: false
    })
  },

  toStudyFinish() {
    wx.navigateTo({
      url: '/pages/studyFinsh/index',
    })
  },

  // 上传课程视频学习信息
  uploadStep(){
    if(this.data.currentTime!==this.data.initialTime){
      wx.request({
        url: API.UpdateProgress,
        header:{
          "Authorization": 'Bearer '+wx.getStorageSync('accessTokenData').accessToken
        },
        method: "put",
        data:{
          playerTimestamp: this.data.currentTime,
          finished: this.data.detailData.finished ? true:this.data.videoDuration - this.data.currentTime <= 1,
          id: this.data.detailData.id,
          progress: this.data.currentTime/this.data.videoDuration
        },
        success: (res) => {
          console.log("调用更新学习状态接口返回的信息是：",res)
          this.setData({
            initialTime: this.data.currentTime
          })
        },
        fail: (err) => {
        },
        complete:()=>{
          
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("课程视频学习页面的course id是：", options.id)
    this.setData({
      courseId: options.id
    })

    HTTP.get(API.GetCourseDetail, { id: options.id }).then(data => {
      console.log('onLoad data :', options.id, data)
      this.setData({
        detailData: data.data,
        stared: data.data.stared,
        liked: data.data.liked,
        // 增加视频时之保留视频名称，播放时增加域名https://dev.yueyoumap.com/{filename}即可
        // video: "https://dev.yueyoumap.com/"+data.data.items.filter(item => item.type == 2)[0].demo,
        video: data.data.items.filter(item => item.type == 2)[0].demo,
        initialTime: data.data.playerTimestamp
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("隐藏页面",this.data.currentTime)
    this.uploadStep()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("卸载页面",this.data.currentTime)
    this.uploadStep()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})